import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import legacy from '@vitejs/plugin-legacy';
import viteCompression from 'vite-plugin-compression';
import { resolve } from 'path';

const mockApiUrl = 'https://console-mock.apipost.cn/app/mock/project/79ea3b05-05f2-4f42-b40d-3d7f56281f27'; // mock接口
const devApiUrl = 'http://api-dev.scrm.keyid.cn'; // 开发环境接口

export default ({ mode, command }) =>
    defineConfig({
        plugins: [
            vue(),
            vueJsx(),
            legacy({
                targets: ['defaults', 'not IE 11'],
                polyfills: ['es.promise.finally', 'es/map', 'es/set'],
                modernPolyfills: ['es.promise.finally']
            }),
            viteCompression({
                threshold: 512000 // 对大于 512kb 的文件进行压缩
            })
        ],
        server: {
            host: '0.0.0.0',
            port: 8080,
            open: true,
            proxy: {
                '/zw-api': {
                    target: mode === 'mock' ? mockApiUrl : devApiUrl,
                    changeOrigin: true,
                    rewrite: path => path.replace(/^\/zw-api/, '')
                },
                '/ws': {
                    target: 'https://apis.map.qq.com',
                    changeOrigin: true
                }
            }
        },
        resolve: {
            alias: {
                '@': resolve(__dirname, './src'),
                '~': resolve(__dirname, './src'),
                'element-plus': '@zhongwan/element-plus'
            }
        },
        build: {
            minify: 'terser',
            terserOptions: {
                compress: {
                    // 生产/测试环境移除console和debugger
                    drop_console: command === 'build' && (mode === 'prod' || mode === 'test'),
                    drop_debugger: command === 'build' && (mode === 'prod' || mode === 'test')
                }
            },
            rollupOptions: {
                output: {
                    manualChunks: {
                        echarts: ['echarts'],
                        lodash: ['lodash'],
                        'benz-amr-recorder': ['benz-amr-recorder'],
                        '@zhongwan/element-plus': ['@zhongwan/element-plus']
                    }
                }
            }
        }
    });
